﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MySql.Data.MySqlClient;

namespace IWS.SiteManager.Web
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	public class MvcApplication : System.Web.HttpApplication
	{
		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
			routes.IgnoreRoute("Views/{*pathInfo}");

			//routes.IgnoreRoute("favicon.ico");
			routes.IgnoreRoute("content/{*pathInfo}");

			//manually setting up controller routes due to the nature of the REST content router. 
			routes.MapRoute(
				 "Admin",                                              // Route name
				 "Manage/{action}/{id}",                           // URL with parameters
				 new { controller = "Manage", action = "Index", id = string.Empty }  // Parameter defaults
			);

			routes.MapRoute(
				 "Account",                                              // Route name
				 "Account/{action}/{id}",                           // URL with parameters
				 new { controller = "Account", action = "Index", id = string.Empty }  // Parameter defaults
			);

			// need a simple db check before we try to access it.  if this is a new install the routes need to be RE Registered after the database is setup. 
			//this should happen because we're rewriting the web.config during install.
			var sitemanager_con_string = Core.DBFactory.GetDefaultConnectionString();
			if (sitemanager_con_string != null)
			{
				string default_section = "Home";
				using (MySqlConnection conn = new MySqlConnection(sitemanager_con_string))
				{
					conn.Open();
					MySqlCommand cmd = new MySqlCommand("select value from `Setting` where `ID` = @ID", conn);
					cmd.CommandType = System.Data.CommandType.Text;
					cmd.Parameters.Add(new MySqlParameter("@ID", Core.Constants.DefaultSection));
					default_section = cmd.ExecuteScalar() as string;
					conn.Close();
				}
				routes.MapRoute(
					 "Content Permalink",                                              // Route name
					 "View/{section}/{permalink}",                           // URL with parameters
					 new { controller = "Content", action = "ViewByPermalink", section = default_section, permalink = "" }  // Parameter defaults
				);
			}

			routes.MapRoute(
				"Default",
				"{controller}/{action}/{id}",
				new { controller = "Content", action = "Index", id = string.Empty }
			);
		}

		protected void Application_Start()
		{
			RegisterRoutes(RouteTable.Routes);
		}
	}
}